#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import webapp2
import cgi
import jinja2
import os
import datetime

from google.appengine.ext import db
from google.appengine.api import users



class Product(db.Model):
	name = db.StringProperty()
	orderno = db.StringProperty()
	start = db.DateProperty()
	end = db.DateProperty()
	clientid = db.IntegerProperty()
	closed = db.BooleanProperty()


class Component(db.Model):
	product = db.ReferenceProperty(Product, collection_name='components')
	name = db.StringProperty()
	japaneseName = db.StringProperty()


jinja_environment = jinja2.Environment(
	loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class MainHandler(webapp2.RequestHandler):
	def get(self):
		user = users.get_current_user()

		if user:
			self.doExecute(user, users.create_logout_url(self.request.uri))
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def doExecute(self, user, logout_url):
		products = db.GqlQuery("SELECT * FROM Product");
		template_values = {
			'user': user,
			'logout_url': logout_url,
			'url': '/manage/componentManager',
			'products': products,
		}

		template = jinja_environment.get_template('componentManager.html')
		self.response.out.write(template.render(template_values))

class AddHandler(webapp2.RequestHandler):
	def post(self):
		user = users.get_current_user()
		if not user:
			self.redirect('/manage/componentManager')

		orderno = self.request.get('orderno')
		name = self.request.get('name')
		jpname = self.request.get('japaneseName')

		p = Product.gql("WHERE orderno=:1", orderno).get()
		c = Component(product=p, name=name, japaneseName=jpname).put()
		
		self.redirect('/manage/componentManager')

app = webapp2.WSGIApplication([
	('/manage/componentManager', MainHandler),
	('/manage/componentManager/add', AddHandler),
], debug=True)
